<template>
    <div>
        <el-dialog :visible.sync="editDialogVisible" title="修改管理员信息">
            <el-form :model="manager" :rules="rules" ref="managerForm" label-width="100px" style="width: 500px; margin-left: 180px"
                     size="small ">
                <el-form-item label="用户名" prop="manAccount">
                    <el-input v-model="manager.manAccount" placeHolder="请输入管理员用户名"/>
                </el-form-item>
                <el-form-item label="密  码" prop="manPwd">
                    <el-input v-model="manager.manPwd" type="password" placeHolder="请输入密码"/>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPass">
                    <el-input v-model="manager.checkPass" type="password" placeHolder="请再次输入密码"/>
                </el-form-item>
                <el-form-item label="身份证" prop="manId">
                    <el-input v-model="manager.manId" placeHolder="请输入身份证号"/>
                </el-form-item>
                <el-form-item label="性别" prop="manSex">
                    <el-radio-group v-model="manager.manSex">
                        <el-radio label="m">男</el-radio>
                        <el-radio label="f">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="手机号" prop="manTelNumber">
                    <el-input v-model="manager.manTelNumber" placeHolder="请输入手机号"/>
                </el-form-item>
                <el-form-item label="email" prop="manEmail">
                    <el-input v-model="manager.manEmail" placeHolder="email"/>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="update" :disabled="btnSts">确定修改</el-button>
                    <el-button @click="editDialogVisible=false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <el-breadcrumb separator-class="el-icon-arrow-right"
                       style="background-color:white;padding: 8px;margin-bottom: 20px">
            <el-breadcrumb-item>首页</el-breadcrumb-item>
            <el-breadcrumb-item>人员用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        </el-breadcrumb>
        <el-table :data="managerList" width="100%">
            <el-table-column prop="manAccount" label="账户名"></el-table-column>
            <el-table-column prop="manId" label="身份证"></el-table-column>
            <el-table-column prop="manSex" label="性别" :formatter="sexFormatter"></el-table-column>
            <el-table-column prop="manTelNumber" label="手机号"></el-table-column>
            <el-table-column prop="manEmail" label="email"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" @click="editManager(scope.$index,scope.row)">编辑</el-button>
                    <el-button type="danger" size="mini" @click="deleteManager(scope.$index,scope.row)">删除</el-button>
                </template>
            </el-table-column>

        </el-table>
        <el-pagination
                style="margin-top: 10px"
                background
                layout="prev, pager, next"
                :current-page.sync="pageInfo.pageNum"
                :page-count="pageInfo.pages"
                :page-size="pageInfo.pageSize"
                :total="pageInfo.total"
                @current-change="this.findList">
        </el-pagination>

    </div>
</template>

<script>
    export default {
        name: "ManagerList",
        //created生命周期函数，created在页面加载完毕后但是还没渲染的时候执行
        created() {
            this.findList();


        },
        methods: {
            /**
             * 获取表格内数据
             */
            findList() {
                axios.post("/manager/page", {
                    pageNum:this.pageInfo.pageNum,
                    pageSize:this.pageInfo.pageSize,
                    condition:{}
                }).then(resp => {
                    // console.log(resp.data);
                    this.pageInfo.pageSize=resp.data.pageSize;
                    this.pageInfo.pageNum=resp.data.pageNum;
                    this.pageInfo.total=resp.data.total;
                    this.pageInfo.pages=resp.data.pages;
                    this.managerList=resp.data.list;
                })
            },


            deleteManager(index, row) {
                this.$confirm('此操作将永久删除该管理员, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.delete("/manager/delete/"+row.id).then(resp=>{
                        if(resp.data==="success") {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            })

                        }else{
                            this.$message({
                                type: 'error',
                                message: 'this.findList();删除失败!'
                            })
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },
            sexFormatter(row/*,column*/) {
                //如果是m，返回：男，否则返回女
                return row.manSex === 'm' ? "男" : "女";
            },
            editManager(index, row) {
                //弹出一个可以修改输入用户信息的表单窗口
                this.vaAccout=row.manAccount;
                this.editDialogVisible = true;
                //克隆row
                let clone = _.clone(row);
                clone.checkPass = "";
                this.manager = clone;
            },
            update() {
                //将提交按钮设置为不可用状态 按钮动态加disable属性
                this.btnSts = true;
                //1、先验证表单格式没问题了，再允许发送请求
                this.$refs['managerForm'].validate((valid) => {
                    if (valid) {
                        //clone对象
                        let payLoad = _.clone(this.manager);
                        //删除payLoad的checkPass属性
                        delete payLoad.checkPass;
                        // 进行表单的提交
                        axios.post("/manager/save", payLoad).then(response => {
                            this.btnSts = false;
                            if (response.data === 'success') {
                                this.$notify({
                                    title: "提示",
                                    message: "用户保存成功",
                                    type: "success"
                                });
                                //一旦提交成功，自动关闭窗口
                                this.editDialogVisible = false;
                                this.findList();
                            }
                        })
                    } else {
                        this.btnSts = false;
                        return false;
                    }
                })
            }
        },
        data() {
            let validAccount = (rule, value, callback) =>{
                if(this.vaAccout==value){
                    return callback();
                }
                axios.get("/manager/valid/" + value).then(response => {
                    if (response.data.dup == true) {
                        callback(new Error("用户名重复"));
                    } else {
                        callback();
                    }
                })
            };


            let validPwd = (rule, value, callback) => {
                //判断密码长度6-10之间，不能为空
                if (!value || value === '') {
                    return callback(new Error("密码不能为空"));
                }
                if (value.length < 6 || value.length > 20) {
                    return callback(new Error("密码长度6-20之间"));
                }
                return callback();
            };
            let validPwd2 = (rule, value, callback) => {
                if (this.manager.manPwd !== value) {
                    return callback(new Error("两次密码不一致"));
                } else {
                    return callback();
                }
            };
            //通过正则表达式验证身份证
            let validId = (rules, value, callback) => {
                if (!value || value === '') {
                    return callback(new Error("身份证不能为空"))
                }
                let pattern = /^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|31)|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/;
                if (!pattern.test(value)) {
                    return callback(new Error("身份证格式错误！请重新输入！"))
                }
                return callback();
            };
            let validPhone = (rules, value, callback) => {
                if (!value || value === '') {
                    return callback(new Error("手机号不能为空！"))
                }
                let pattern = /^1[3|4|5|8][0-9]\d{8}$/;
                if (!pattern.test(value)) {
                    return callback(new Error("手机号格式错误！请重新输入"));
                }
                return callback();
            };
            let validEmail = (rule, value, callback) => {
                if (!value || value === '') {
                    return callback(new Error("邮箱不能为空"));
                }
                let pattern = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
                if (!pattern.test(value)) {
                    return callback(new Error("邮箱格式错误"))
                }
                return callback();
            };
            return {
                //pageInfo对象实际是从后台查询得到的，代表了分页必要的信息
                pageInfo:{
                    pageNum:1, /*当前是那一页*/
                    pageSize:5, /*每页展示多少条*/
                    pages:20, /*总共有多少页*/
                    total:100 /*总共有多少条数据*/
                },
                vaAccout:"",/*记录原来*/
                editDialogVisible: false,
                manager: {},
                btnSts: false,
                managerList: [],
                rules: {
                    manAccount: [
                        {required: true, message: '用户名不能为空', trigger: 'blur'},
                        {min: 6, max: 20, message: '用户名6-20之间', trigger: 'blur'},
                        {validator: validAccount, trigger: 'blur'}
                    ],
                    manPwd: [
                        {validator: validPwd, trigger: 'blur'}
                    ],
                    checkPass: [
                        {validator: validPwd2, trigger: 'blur'}
                    ],
                    manId: [
                        {validator: validId, trigger: "blur"}
                    ],
                    manSex: [
                        {required: true, message: "请选择性别", trigger: "blur"}
                    ],
                    manTelNumber: [
                        {validator: validPhone, trigger: "blur"}
                    ],
                    manEmail: [
                        {validator: validEmail, trigger: "blur"}
                    ]
                }

            }
        }
    }
</script>

<style scoped>

</style>